CREATE NONCLUSTERED INDEX IX_Channel_MeterID_MeasurementTypeID_MeasurementCharacteristicID_PhaseID_HarmonicGroup
ON Channel(MeterID ASC, MeasurementTypeID, MeasurementCharacteristicID, PhaseID, HarmonicGroup)
GO

CREATE TABLE AssetGroup
(
    ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    Name VARCHAR(200) NOT NULL
)
GO

EXEC sp_rename 'DeviceFilter', 'DeviceFilter_org'
GO

CREATE TABLE DeviceFilter
(
    ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    UserAccount VARCHAR(500) NOT NULL,
    Name NVARCHAR(500) NOT NULL,
    FilterExpression NVARCHAR(MAX) NOT NULL,
    AssetGroupID INT NOT NULL
)
GO

INSERT INTO DeviceFilter
SELECT UserAccount, DeviceFilter_org.Name, FilterExpression, AssetGroup.ID
FROM
    DeviceFilter_org JOIN
    MeterGroup ON DeviceFilter_org.MeterGroupID = MeterGroup.ID JOIN
    AssetGroup ON
        MeterGroup.Name = AssetGroup.Name OR
        (MeterGroup.Name = 'AllMeters' AND AssetGroup.Name = 'AllAssets')
GO

CREATE TABLE MeterAssetGroup
(
    ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    MeterID INT NOT NULL REFERENCES Meter(ID),
    AssetGroupID INT NOT NULL REFERENCES AssetGroup(ID)
)
GO

CREATE NONCLUSTERED INDEX IX_MeterAssetGroup_MeterID
ON MeterAssetGroup(MeterID ASC)
GO

CREATE NONCLUSTERED INDEX IX_MeterAssetGroup_AssetGroupID
ON MeterAssetGroup(AssetGroupID ASC)
GO

CREATE TRIGGER Meter_AugmentAllAssetsGroup
ON Meter
AFTER INSERT
AS BEGIN
    SET NOCOUNT ON;

    INSERT INTO MeterAssetGroup(MeterID, AssetGroupID)
    SELECT Meter.ID, AssetGroup.ID
    FROM inserted Meter CROSS JOIN AssetGroup
    WHERE AssetGroup.Name = 'AllAssets'
END
GO

CREATE TABLE LineAssetGroup
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    LineID INT NOT NULL REFERENCES Line(ID),
    AssetGroupID INT NOT NULL REFERENCES AssetGroup(ID),
)
GO

CREATE NONCLUSTERED INDEX IX_LineAssetGroup_LineID
ON LineAssetGroup(LineID ASC)
GO

CREATE NONCLUSTERED INDEX IX_LineAssetGroup_AssetGroupID
ON LineAssetGroup(AssetGroupID ASC)
GO

CREATE TRIGGER Line_AugmentAllAssetsGroup
ON Line
AFTER INSERT
AS BEGIN
    SET NOCOUNT ON;

    INSERT INTO LineAssetGroup(LineID, AssetGroupID)
    SELECT Line.ID, AssetGroup.ID
    FROM inserted Line CROSS JOIN AssetGroup
    WHERE AssetGroup.Name = 'AllAssets'
END
GO

CREATE TABLE MaintenanceWindow
(
    ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    MeterID INT NOT NULL REFERENCES Meter(ID),
    StartTime DATETIME,
    EndTime DATETIME
)
GO

INSERT INTO DataOperation(AssemblyName, TypeName, LoadOrder) VALUES('FaultData.dll', 'FaultData.DataOperations.DataPusherOperation', 11)
GO

INSERT INTO AssetGroup(Name) VALUES('AllAssets')
GO

INSERT INTO AssetGroup(Name)
SELECT Name
FROM MeterGroup
WHERE Name <> 'AllMeters'
GO

INSERT INTO MeterAssetGroup
SELECT MeterMeterGroup.MeterID, AssetGroup.ID
FROM
    MeterMeterGroup JOIN
    MeterGroup ON MeterMeterGroup.MeterGroupID = MeterGroup.ID JOIN
    AssetGroup ON
        MeterGroup.Name = AssetGroup.Name OR
        (MeterGroup.Name = 'AllMeters' AND AssetGroup.Name = 'AllAssets')
GO

ALTER TABLE UserAccount
ADD CONSTRAINT UQ_UserAccount_Name UNIQUE(Name)
GO

ALTER TABLE UserAccount
ADD PhoneConfirmed BIT NOT NULL DEFAULT 0
GO

ALTER TABLE UserAccount
ADD EmailConfirmed BIT NOT NULL DEFAULT 0
GO

ALTER TABLE UserAccount
ADD Approved BIT NOT NULL DEFAULT 0
GO

UPDATE UserAccount
SET
    EmailConfirmed = 1,
    Approved = 1
GO

CREATE TABLE UserAccountAssetGroup
(
    ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    UserAccountID UNIQUEIDENTIFIER NOT NULL REFERENCES UserAccount(ID),
    AssetGroupID INT NOT NULL REFERENCES AssetGroup(ID),
    Dashboard BIT NOT NULL DEFAULT 1,
    Email BIT NOT NULL DEFAULT 0
)
GO

INSERT INTO UserAccountAssetGroup
SELECT UserAccountMeterGroup.UserAccountID, AssetGroup.ID, 1, 1
FROM
    UserAccountMeterGroup JOIN
    MeterGroup ON UserAccountMeterGroup.MeterGroupID = MeterGroup.ID JOIN
    AssetGroup ON
        MeterGroup.Name = AssetGroup.Name OR
        (MeterGroup.Name = 'AllMeters' AND AssetGroup.Name = 'AllAssets')
GO

CREATE TRIGGER UserAccount_AugmentAllAssetsGroup
ON UserAccount
AFTER INSERT
AS BEGIN
    SET NOCOUNT ON;

    INSERT INTO UserAccountAssetGroup(UserAccountID, AssetGroupID)
    SELECT UserAccount.ID, AssetGroup.ID
    FROM inserted UserAccount CROSS JOIN AssetGroup
    WHERE AssetGroup.Name = 'AllAssets'
END
GO

ALTER TABLE XSLTemplate
ADD CONSTRAINT UQ_XSLTemplate_Name UNIQUE(Name)
GO

ALTER TABLE EmailType
ADD SMS BIT NOT NULL DEFAULT 0
GO

CREATE TABLE EventEmailParameters
(
    ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    EmailTypeID INT NOT NULL UNIQUE REFERENCES EmailType(ID),
    TriggersEmailSQL VARCHAR(MAX) NOT NULL DEFAULT 'SELECT 0',
    EventDetailSQL VARCHAR(MAX) NOT NULL DEFAULT 'SELECT '''' FOR XML PATH(''EventDetail''), TYPE',
    MinDelay FLOAT NOT NULL DEFAULT 10,
    MaxDelay FLOAT NOT NULL DEFAULT 60
)
GO

CREATE TABLE UserAccountEmailType
(
    ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    UserAccountID UNIQUEIDENTIFIER NOT NULL REFERENCES UserAccount(ID),
    EmailTypeID INT NOT NULL REFERENCES EmailType(ID)
)
GO

INSERT INTO UserAccountEmailType
SELECT EmailGroupUserAccount.UserAccountID, EmailGroupType.EmailTypeID
FROM
    EmailGroupUserAccount JOIN
    EmailGroupType ON EmailGroupUserAccount.EmailGroupID = EmailGroupType.EmailGroupID
GO

INSERT INTO EventEmailParameters(EmailTypeID)
SELECT EmailType.ID
FROM
    EmailType JOIN
    EmailCategory ON EmailType.EmailCategoryID = EmailCategory.ID
WHERE EmailCategory.Name = 'Event'
GO

UPDATE EventEmailParameters
SET TriggersEmailSQL = 'SELECT
    CASE WHEN EventType.Name = ''Fault''
        THEN 1
        ELSE 0
    END
FROM
    Event JOIN
    EventType ON Event.EventTypeID = EventType.ID
WHERE Event.ID = {0}'
WHERE EmailTypeID = (SELECT ID FROM EmailType WHERE XSLTemplateID = (SELECT ID FROM XSLTemplate WHERE Name = 'Default Fault'))
GO

UPDATE EventEmailParameters
SET TriggersEmailSQL = 'SELECT
    CASE WHEN EventType.Name IN(''Fault'', ''RecloseIntoFault'')
        THEN 1
        ELSE 0
    END
FROM
    Event JOIN
    EventType ON Event.EventTypeID = EventType.ID
WHERE Event.ID = {0}'
WHERE EmailTypeID = (SELECT ID FROM EmailType WHERE XSLTemplateID = (SELECT ID FROM XSLTemplate WHERE Name = 'GTC Faults'))
GO

UPDATE EventEmailParameters
SET TriggersEmailSQL = 'SELECT
    CASE WHEN COUNT(*) > 0
        THEN 1
        ELSE 0
    END
FROM
    BreakerOperation JOIN
    BreakerOperationType ON BreakerOperation.BreakerOperationTypeID = BreakerOperationType.ID
WHERE
    BreakerOperation.EventID = {0} AND
    BreakerOperationType.Name = ''Late'''
WHERE EmailTypeID = (SELECT ID FROM EmailType WHERE XSLTemplateID = (SELECT ID FROM XSLTemplate WHERE Name = 'GTC Breakers'))
GO

UPDATE EventEmailParameters
SET EventDetailSQL = 'DECLARE @timeTolerance FLOAT = (SELECT CAST(Value AS FLOAT) FROM Setting WHERE Name = ''TimeTolerance'')
DECLARE @lineID INT
DECLARE @startTime DATETIME2
DECLARE @endTime DATETIME2

SELECT
    @lineID = LineID,
    @startTime = dbo.AdjustDateTime2(StartTime, -@timeTolerance),
    @endTime = dbo.AdjustDateTime2(EndTime, @timeTolerance)
FROM Event
WHERE ID = {0}

SELECT *
INTO #lineEvent
FROM Event
WHERE
    Event.LineID = @lineID AND
    Event.EndTime >= @startTime AND
    Event.StartTime <= @endTime

SELECT
    ROW_NUMBER() OVER(PARTITION BY Event.MeterID ORDER BY FaultSummary.Inception) AS FaultNumber,
    FaultSummary.ID AS FaultSummaryID,
    Meter.AssetKey AS MeterKey,
    Meter.Name AS MeterName,
    MeterLocation.AssetKey as StationKey,
    MeterLocation.Name AS StationName,
    Line.AssetKey AS LineKey,
    MeterLine.LineName,
    FaultSummary.FaultType,
    FaultSummary.Inception,
    FaultSummary.DurationCycles,
    FaultSummary.DurationSeconds * 1000.0 AS DurationMilliseconds,
    CASE WHEN FaultSummary.PrefaultCurrent <> -1E308 THEN FORMAT(FaultSummary.PrefaultCurrent, ''0.##########'') ELSE ''NaN'' END AS PrefaultCurrent,
    CASE WHEN FaultSummary.PostfaultCurrent <> -1E308 THEN FORMAT(FaultSummary.PostfaultCurrent, ''0.##########'') ELSE ''NaN'' END AS PostfaultCurrent,
    FaultSummary.ReactanceRatio,
    FaultSummary.CurrentMagnitude AS FaultCurrent,
    FaultSummary.Algorithm,
    FaultSummary.Distance AS SingleEndedDistance,
    DoubleEndedFaultSummary.Distance AS DoubleEndedDistance,
    DoubleEndedFaultSummary.Angle AS DoubleEndedAngle,
    RIGHT(DataFile.FilePath, CHARINDEX(CHAR(92), REVERSE(DataFile.FilePath)) - 1) AS FileName,
    FaultSummary.EventID,
    Event.StartTime AS EventStartTime,
    Event.EndTime AS EventEndTime
INTO #summaryData
FROM
    #lineEvent Event JOIN
    EventType ON
        Event.EventTypeID = EventType.ID AND
        EventType.Name = ''Fault'' JOIN
    FaultSummary ON
        FaultSummary.EventID = Event.ID AND
        FaultSummary.IsSelectedAlgorithm <> 0 JOIN
    DataFile ON DataFile.FileGroupID = Event.FileGroupID JOIN
    Meter ON Event.MeterID = Meter.ID JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID JOIN
    MeterLine ON MeterLine.MeterID = Meter.ID AND MeterLine.LineID = Event.LineID JOIN
    Line ON MeterLine.LineID = Line.ID LEFT OUTER JOIN
    DoubleEndedFaultDistance ON DoubleEndedFaultDistance.LocalFaultSummaryID = FaultSummary.ID LEFT OUTER JOIN
    DoubleEndedFaultSummary ON DoubleEndedFaultSummary.ID = DoubleEndedFaultDistance.ID
WHERE
    DataFile.FilePath LIKE ''%.DAT'' OR
    DataFile.FilePath LIKE ''%.D00'' OR
    DataFile.FilePath LIKE ''%.PQD'' OR
    DataFile.FilePath LIKE ''%.RCD'' OR
    DataFile.FilePath LIKE ''%.RCL'' OR
    DataFile.FilePath LIKE ''%.SEL'' OR
    DataFile.FilePath LIKE ''%.EVE'' OR
    DataFile.FilePath LIKE ''%.CEV''

DECLARE @url VARCHAR(MAX) = (SELECT Value FROM DashSettings WHERE Name = ''System.URL'')

SELECT
    (
        SELECT ID AS [@id]
        FROM #lineEvent
        FOR XML PATH(''Event''), TYPE
    ) AS [Events],
    (
        SELECT
            FaultNumber AS [@num],
            (
                SELECT
                    MeterKey,
                    MeterName,
                    StationKey,
                    StationName,
                    LineKey,
                    LineName,
                    FaultType,
                    Inception,
                    DurationCycles,
                    DurationMilliseconds,
                    PrefaultCurrent,
                    PostfaultCurrent,
                    ReactanceRatio,
                    FaultCurrent,
                    Algorithm,
                    SingleEndedDistance,
                    DoubleEndedDistance,
                    DoubleEndedAngle,
                    EventStartTime,
                    EventEndTime,
                    FileName,
                    EventID,
                    FaultSummaryID AS FaultID
                FROM #summaryData
                WHERE FaultNumber = Fault.FaultNumber
                FOR XML PATH(''SummaryData''), TYPE
            )
        FROM
        (
            SELECT DISTINCT FaultNumber
            FROM #summaryData
        ) Fault
        FOR XML PATH(''Fault''), TYPE
    ) AS [Faults],
    MeterLine.LineName AS [Line/Name],
    Line.AssetKey AS [Line/AssetKey],
    FORMAT(Line.Length, ''0.##########'') AS [Line/Length],
    FORMAT(SQRT(LineImpedance.R1 * LineImpedance.R1 + LineImpedance.X1 * LineImpedance.X1), ''0.##########'') AS [Line/Z1],
    CASE LineImpedance.R1 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2(LineImpedance.X1, LineImpedance.R1) * 180 / PI(), ''0.##########'') END AS [Line/A1],
    FORMAT(LineImpedance.R1, ''0.##########'') AS [Line/R1],
    FORMAT(LineImpedance.X1, ''0.##########'') AS [Line/X1],
    FORMAT(SQRT(LineImpedance.R0 * LineImpedance.R0 + LineImpedance.X0 * LineImpedance.X0), ''0.##########'') AS [Line/Z0],
    CASE LineImpedance.R0 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2(LineImpedance.X0, LineImpedance.R0) * 180 / PI(), ''0.##########'') END AS [Line/A0],
    FORMAT(LineImpedance.R0, ''0.##########'') AS [Line/R0],
    FORMAT(LineImpedance.X0, ''0.##########'') AS [Line/X0],
    FORMAT(SQRT(POWER((2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0, 2) + POWER((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, 2)), ''0.##########'') AS [Line/ZS],
    CASE 2.0 * LineImpedance.R1 + LineImpedance.R0 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, (2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0) * 180 / PI(), ''0.##########'') END AS [Line/AS],
    FORMAT((2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0, ''0.##########'') AS [Line/RS],
    FORMAT((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, ''0.##########'') AS [Line/XS],
    @url AS [PQDashboard]
FROM
    Event JOIN
    Line ON Event.LineID = Line.ID JOIN
    MeterLine ON
        MeterLine.MeterID = Event.MeterID AND
        MeterLine.LineID = Event.LineID JOIN
    LineImpedance ON LineImpedance.LineID = Line.ID
WHERE Event.ID = {0}
FOR XML PATH(''EventDetail''), TYPE'
WHERE EmailTypeID = (SELECT ID FROM EmailType WHERE XSLTemplateID = (SELECT ID FROM XSLTemplate WHERE Name = 'Default Fault'))
GO

UPDATE EventEmailParameters
SET EventDetailSQL = 'DECLARE @timeTolerance FLOAT = (SELECT CAST(Value AS FLOAT) FROM Setting WHERE Name = ''TimeTolerance'')
DECLARE @lineID INT
DECLARE @startTime DATETIME2
DECLARE @endTime DATETIME2

SELECT
    @lineID = LineID,
    @startTime = dbo.AdjustDateTime2(StartTime, -@timeTolerance),
    @endTime = dbo.AdjustDateTime2(EndTime, @timeTolerance)
FROM Event
WHERE ID = {0}

SELECT *
INTO #lineEvent
FROM Event
WHERE
    Event.LineID = @lineID AND
    Event.EndTime >= @startTime AND
    Event.StartTime <= @endTime

SELECT
    ROW_NUMBER() OVER(PARTITION BY Event.MeterID ORDER BY FaultSummary.Inception) AS FaultNumber,
    FaultSummary.ID AS FaultSummaryID,
    Meter.AssetKey AS MeterKey,
    Meter.Name AS MeterName,
    MeterLocation.AssetKey as StationKey,
    MeterLocation.Name AS StationName,
    Line.AssetKey AS LineKey,
    MeterLine.LineName,
    FaultSummary.FaultType,
    FaultSummary.Inception,
    FaultSummary.DurationCycles,
    FaultSummary.DurationSeconds * 1000.0 AS DurationMilliseconds,
    FaultSummary.PrefaultCurrent,
    FaultSummary.PostfaultCurrent,
    FaultSummary.ReactanceRatio,
    FaultSummary.CurrentMagnitude AS FaultCurrent,
    FaultSummary.Algorithm,
    FaultSummary.Distance AS SingleEndedDistance,
    DoubleEndedFaultSummary.Distance AS DoubleEndedDistance,
    DoubleEndedFaultSummary.Angle AS DoubleEndedAngle,
    RIGHT(DataFile.FilePath, CHARINDEX(CHAR(92), REVERSE(DataFile.FilePath)) - 1) AS FileName,
    RIGHT(DataFile.FilePath, CHARINDEX('','', REVERSE(DataFile.FilePath)) - 1) AS ShortFileName,
    FaultSummary.EventID,
    Event.StartTime AS EventStartTime,
    Event.EndTime AS EventEndTime
INTO #summaryData
FROM
    #lineEvent Event JOIN
    FaultSummary ON
        FaultSummary.EventID = Event.ID AND
        FaultSummary.IsSelectedAlgorithm <> 0 AND
        FaultSummary.IsSuppressed = 0 LEFT OUTER JOIN
    DataFile ON DataFile.FileGroupID = Event.FileGroupID JOIN
    Meter ON Event.MeterID = Meter.ID JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID JOIN
    MeterLine ON MeterLine.MeterID = Meter.ID AND MeterLine.LineID = Event.LineID JOIN
    Line ON MeterLine.LineID = Line.ID LEFT OUTER JOIN
    DoubleEndedFaultDistance ON DoubleEndedFaultDistance.LocalFaultSummaryID = FaultSummary.ID LEFT OUTER JOIN
    DoubleEndedFaultSummary ON DoubleEndedFaultSummary.ID = DoubleEndedFaultDistance.ID
WHERE
    DataFile.FilePath LIKE ''%.DAT'' OR
    DataFile.FilePath LIKE ''%.D00'' OR
    DataFile.FilePath LIKE ''%.PQD'' OR
    DataFile.FilePath LIKE ''%.RCD'' OR
    DataFile.FilePath LIKE ''%.RCL'' OR
    DataFile.FilePath LIKE ''%.SEL'' OR
    DataFile.FilePath LIKE ''%.EVE'' OR
    DataFile.FilePath LIKE ''%.CEV''

DECLARE @url VARCHAR(MAX) = (SELECT Value FROM DashSettings WHERE Name = ''System.URL'')

SELECT
    (
        SELECT ID AS [@id]
        FROM #lineEvent
        FOR XML PATH(''Event''), TYPE
    ) AS [Events],
    (
        SELECT
            FaultNumber AS [@num],
            (
                SELECT
                    MeterKey,
                    MeterName,
                    StationKey,
                    StationName,
                    LineKey,
                    LineName,
                    FaultType,
                    Inception,
                    DurationCycles,
                    DurationMilliseconds,
                    PrefaultCurrent,
                    PostfaultCurrent,
                    ReactanceRatio,
                    FaultCurrent,
                    Algorithm,
                    SingleEndedDistance,
                    DoubleEndedDistance,
                    DoubleEndedAngle,
                    EventStartTime,
                    EventEndTime,
                    FileName,
                    ShortFileName,
                    EventID,
                    FaultSummaryID AS FaultID
                FROM #summaryData
                WHERE FaultNumber = Fault.FaultNumber
                FOR XML PATH(''SummaryData''), TYPE
            )
        FROM
        (
            SELECT DISTINCT FaultNumber
            FROM #summaryData
        ) Fault
        FOR XML PATH(''Fault''), TYPE
    ) AS [Faults],
    MeterLine.LineName AS [Line/Name],
    Line.AssetKey AS [Line/AssetKey],
    FORMAT(Line.Length, ''0.##########'') AS [Line/Length],
    FORMAT(SQRT(LineImpedance.R1 * LineImpedance.R1 + LineImpedance.X1 * LineImpedance.X1), ''0.##########'') AS [Line/Z1],
    CASE LineImpedance.R1 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2(LineImpedance.X1, LineImpedance.R1) * 180 / PI(), ''0.##########'') END AS [Line/A1],
    FORMAT(LineImpedance.R1, ''0.##########'') AS [Line/R1],
    FORMAT(LineImpedance.X1, ''0.##########'') AS [Line/X1],
    FORMAT(SQRT(LineImpedance.R0 * LineImpedance.R0 + LineImpedance.X0 * LineImpedance.X0), ''0.##########'') AS [Line/Z0],
    CASE LineImpedance.R0 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2(LineImpedance.X0, LineImpedance.R0) * 180 / PI(), ''0.##########'') END AS [Line/A0],
    FORMAT(LineImpedance.R0, ''0.##########'') AS [Line/R0],
    FORMAT(LineImpedance.X0, ''0.##########'') AS [Line/X0],
    FORMAT(SQRT(POWER((2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0, 2) + POWER((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, 2)), ''0.##########'') AS [Line/ZS],
    CASE 2.0 * LineImpedance.R1 + LineImpedance.R0 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, (2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0) * 180 / PI(), ''0.##########'') END AS [Line/AS],
    FORMAT((2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0, ''0.##########'') AS [Line/RS],
    FORMAT((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, ''0.##########'') AS [Line/XS],
    @url AS [PQDashboard]
FROM
    Event JOIN
    Line ON Event.LineID = Line.ID JOIN
    MeterLine ON
        MeterLine.MeterID = Event.MeterID AND
        MeterLine.LineID = Event.LineID JOIN
    LineImpedance ON LineImpedance.LineID = Line.ID
WHERE Event.ID = {0}
FOR XML PATH(''EventDetail''), TYPE'
WHERE EmailTypeID = (SELECT ID FROM EmailType WHERE XSLTemplateID = (SELECT ID FROM XSLTemplate WHERE Name = 'GTC Faults'))
GO

UPDATE EventEmailParameters
SET EventDetailSQL = 'DECLARE @timeTolerance FLOAT = (SELECT CAST(Value AS FLOAT) FROM Setting WHERE Name = ''TimeTolerance'')
DECLARE @lineID INT
DECLARE @startTime DATETIME2
DECLARE @endTime DATETIME2

SELECT
    @lineID = LineID,
    @startTime = dbo.AdjustDateTime2(StartTime, -@timeTolerance),
    @endTime = dbo.AdjustDateTime2(EndTime, @timeTolerance)
FROM Event
WHERE ID = {0}

SELECT *
INTO #lineEvent
FROM Event
WHERE
    Event.LineID = @lineID AND
    Event.EndTime >= @startTime AND
    Event.StartTime <= @endTime

SELECT
    ROW_NUMBER() OVER(PARTITION BY BreakerOperation.BreakerNumber ORDER BY BreakerOperation.TripCoilEnergized) AS BreakerOperationNumber,
    BreakerOperation.ID AS BreakerOperationID,
    Meter.AssetKey AS MeterKey,
    MeterLocation.Name AS StationName,
    MeterLine.LineName,
    BreakerOperation.TripCoilEnergized,
    BreakerOperation.BreakerNumber,
    Phase.Name AS Phase,
    BreakerOperation.BreakerTiming,
    BreakerOperation.StatusTiming,
    BreakerOperation.DcOffsetDetected,
    BreakerOperation.BreakerSpeed,
    BreakerOperation.StatusBitChatter,
    RIGHT(DataFile.FilePath, CHARINDEX(CHAR(92), REVERSE(DataFile.FilePath)) - 1) AS FileName,
    RIGHT(DataFile.FilePath, CHARINDEX('','', REVERSE(DataFile.FilePath)) - 1) AS ShortFileName,
    BreakerOperation.EventID,
    Event.StartTime AS EventStartTime,
    Event.EndTime AS EventEndTime
INTO #summaryData
FROM
    #lineEvent Event JOIN
    BreakerOperation ON BreakerOperation.EventID = Event.ID JOIN
    BreakerOperationType ON
        BreakerOperation.BreakerOperationTypeID = BreakerOperationType.ID AND
        BreakerOperationType.Name = ''Late'' JOIN
    Phase ON BreakerOperation.PhaseID = Phase.ID JOIN
    DataFile ON DataFile.FileGroupID = Event.FileGroupID JOIN
    Meter ON Event.MeterID = Meter.ID JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID JOIN
    MeterLine ON MeterLine.MeterID = Meter.ID AND MeterLine.LineID = Event.LineID
WHERE
    DataFile.FilePath LIKE ''%.DAT'' OR
    DataFile.FilePath LIKE ''%.D00'' OR
    DataFile.FilePath LIKE ''%.PQD'' OR
    DataFile.FilePath LIKE ''%.RCD'' OR
    DataFile.FilePath LIKE ''%.RCL'' OR
    DataFile.FilePath LIKE ''%.SEL'' OR
    DataFile.FilePath LIKE ''%.EVE'' OR
    DataFile.FilePath LIKE ''%.CEV''

DECLARE @url VARCHAR(MAX) = (SELECT Value FROM DashSettings WHERE Name = ''System.URL'')

SELECT
    (
        SELECT ID AS [@id]
        FROM #lineEvent
        FOR XML PATH(''Event''), TYPE
    ) AS [Events],
    (
        SELECT
            BreakerOperationNumber AS [@num],
            (
                SELECT
                    MeterKey,
                    StationName,
                    LineName,
                    BreakerNumber,
                    Phase,
                    TripCoilEnergized,
                    BreakerTiming,
                    StatusTiming,
                    DcOffsetDetected,
                    BreakerSpeed,
                    StatusBitChatter,
                    EventStartTime,
                    EventEndTime,
                    FileName,
                    ShortFileName,
                    EventID,
                    BreakerOperationID
                FROM #summaryData
                WHERE BreakerOperationNumber = BreakerOperation.BreakerOperationNumber
                FOR XML PATH(''BreakerOperationData''), TYPE
            )
        FROM
        (
            SELECT DISTINCT BreakerOperationNumber
            FROM #summaryData
        ) BreakerOperation
        FOR XML PATH(''BreakerOperation''), TYPE
    ) AS [BreakerOperations],
    MeterLine.LineName AS [Line/Name],
    Line.AssetKey AS [Line/AssetKey],
    FORMAT(Line.Length, ''0.##########'') AS [Line/Length],
    FORMAT(SQRT(LineImpedance.R1 * LineImpedance.R1 + LineImpedance.X1 * LineImpedance.X1), ''0.##########'') AS [Line/Z1],
    CASE LineImpedance.R1 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2(LineImpedance.X1, LineImpedance.R1) * 180 / PI(), ''0.##########'') END AS [Line/A1],
    FORMAT(LineImpedance.R1, ''0.##########'') AS [Line/R1],
    FORMAT(LineImpedance.X1, ''0.##########'') AS [Line/X1],
    FORMAT(SQRT(LineImpedance.R0 * LineImpedance.R0 + LineImpedance.X0 * LineImpedance.X0), ''0.##########'') AS [Line/Z0],
    CASE LineImpedance.R0 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2(LineImpedance.X0, LineImpedance.R0) * 180 / PI(), ''0.##########'') END AS [Line/A0],
    FORMAT(LineImpedance.R0, ''0.##########'') AS [Line/R0],
    FORMAT(LineImpedance.X0, ''0.##########'') AS [Line/X0],
    FORMAT(SQRT(POWER((2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0, 2) + POWER((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, 2)), ''0.##########'') AS [Line/ZS],
    CASE 2.0 * LineImpedance.R1 + LineImpedance.R0 WHEN 0 THEN ''0'' ELSE FORMAT(ATN2((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, (2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0) * 180 / PI(), ''0.##########'') END AS [Line/AS],
    FORMAT((2.0 * LineImpedance.R1 + LineImpedance.R0) / 3.0, ''0.##########'') AS [Line/RS],
    FORMAT((2.0 * LineImpedance.X1 + LineImpedance.X0) / 3.0, ''0.##########'') AS [Line/XS],
    @url AS [PQDashboard]
FROM
    Event JOIN
    Line ON Event.LineID = Line.ID JOIN
    MeterLine ON
        MeterLine.MeterID = Event.MeterID AND
        MeterLine.LineID = Event.LineID JOIN
    LineImpedance ON LineImpedance.LineID = Line.ID
WHERE Event.ID = {0}
FOR XML PATH(''EventDetail''), TYPE'
WHERE EmailTypeID = (SELECT ID FROM EmailType WHERE XSLTemplateID = (SELECT ID FROM XSLTemplate WHERE Name = 'GTC Breakers'))
GO

DELETE FROM DataOperation
WHERE TypeName = 'FaultData.DataWriters.EventEmailWriter'
GO

CREATE TABLE SnapshotHarmonics
(
    ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    EventID INT NOT NULL REFERENCES Event(ID),
    ChannelID INT NOT NULL REFERENCES Channel(ID),
    SpectralData varchar(max) NULL
)
GO

CREATE NONCLUSTERED INDEX IX_SnapshotHarmonics_EventID
ON SnapshotHarmonics(EventID ASC)
GO

INSERT INTO EventType(Name, Description) VALUES ('Snapshot', 'Snapshot')
GO

CREATE TABLE Unit
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Name VARCHAR(MAX) NOT NULL
)
GO

CREATE TABLE PQMeasurement
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Name VARCHAR(MAX) NOT NULL,
    Description VARCHAR(MAX) NULL,
    UnitID INT NOT NULL REFERENCES Unit(ID),
    MeasurementTypeID INT NOT NULL REFERENCES MeasurementType(ID),
    MeasurementCharacteristicID INT NOT NULL REFERENCES MeasurementCharacteristic(ID),
    PhaseID INT NOT NULL REFERENCES Phase(ID),
    HarmonicGroup INT NOT NULL DEFAULT 0,
    Enabled bit NOT NULL DEFAULT 1
)
GO

CREATE TABLE PQTrendStat
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    MeterID INT NOT NULL REFERENCES Meter(ID),
    PQMeasurementTypeID INT NOT NULL REFERENCES PQMeasurement(ID),
    Date DATE NOT NULL,
    Max FLOAT NULL,
    CP99 FLOAT NULL,
    CP95 FLOAT NULL,
    Avg FLOAT NULL,
    CP05 FLOAT NULL,
    CP01 FLOAT NULL,
    Min FLOAT NULL
)
GO

CREATE NONCLUSTERED INDEX IX_PQTrendStat_Date
ON PQTrendStat(Date ASC)
GO

CREATE NONCLUSTERED INDEX IX_PQTrendStat_MeterID_Date
ON PQTrendStat(MeterID ASC, Date ASC)
GO

CREATE NONCLUSTERED INDEX IX_PQTrendStat_MeterID_PQMeasurementTypeID_Date
ON PQTrendStat(Date DESC, MeterID ASC, PQMeasurementTypeID ASC)
GO

INSERT INTO Unit (Name) VALUES ('Volts')
GO

INSERT INTO Unit (Name) VALUES ('Amps')
GO

INSERT INTO Unit (Name) VALUES ('KW')
GO

INSERT INTO Unit (Name) VALUES ('KVAR')
GO

INSERT INTO Unit (Name) VALUES ('KVA')
GO

INSERT INTO Unit (Name) VALUES ('Per Unit')
GO

INSERT INTO Unit (Name) VALUES ('Percent')
GO

CREATE TABLE StepChangeMeasurement(
    ID INT PRIMARY KEY IDENTITY(1,1),
    PQMeasurementID INT FOREIGN KEY REFERENCES PQMeasurement(ID) NOT NULL,
    Setting FLOAT NULL
)
GO

CREATE NONCLUSTERED INDEX IX_StepChangeMeasurement_PQMeasurement
ON StepChangeMeasurement(PQMeasurementID ASC)
GO

CREATE TABLE StepChangeStat(
    ID INT PRIMARY KEY IDENTITY(1,1),
    MeterID INT FOREIGN KEY REFERENCES Meter(ID) NOT NULL,
    Date Date NOT NULL,
    StepChangeMeasurementID INT FOREIGN KEY REFERENCES StepChangeMeasurement(ID) NOT NULL,
    Value FLOAT NULL
)
GO

CREATE NONCLUSTERED INDEX IX_StepChangeStat_Date
ON StepChangeStat(Date ASC)
GO

CREATE NONCLUSTERED INDEX IX_StepChangeStat_MeterID_Date
ON StepChangeStat(MeterID ASC, Date ASC)
GO

CREATE NONCLUSTERED INDEX IX_StepChangeStat_MeterID_StepChangeMeasurementID_Date
ON StepChangeStat(MeterID ASC,StepChangeMeasurementID ASC, Date ASC)
GO

CREATE TABLE Report
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    MeterID INT NOT NULL REFERENCES Meter(ID),
    Month INT NOT NULL,
    Year INT NOT NULL,
    Results VARCHAR(4) NOT NULL,
    PDF VARBINARY(MAX) NOT NULL,
    CONSTRAINT UC_Report UNIQUE(ID, MeterID, Month, Year)
)
GO

CREATE TABLE EventStat
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    EventID INT NOT NULL REFERENCES Event(ID),
    IMin float NULL,
    IMax float NULL,
    VMin float NULL,
    VMax float NULL,
    I2t float NULL,
    InitialMW float NULL,
    FinalMW float NULL,
    CONSTRAINT UC_EventStat_EventID UNIQUE(EventID)
)
GO

ALTER FUNCTION ComputeHash
(
    @eventID INT,
    @templateID INT
)
RETURNS BIGINT
BEGIN
    DECLARE @md5Hash BINARY(16)

    DECLARE @eventDetailSQL VARCHAR(MAX) =
    (
        SELECT EventDetailSQL
        FROM
            EmailType JOIN
            EventEmailParameters ON EventEmailParameters.EmailTypeID = EmailType.ID
        WHERE EmailType.XSLTemplateID = @templateID
    )

    DECLARE @eventDetail VARCHAR(MAX)
    EXEC sp_executesql @eventDetailSQL, @eventID, @eventDetail OUT

    SELECT @md5Hash = master.sys.fn_repl_hash_binary(CONVERT(VARBINARY(MAX), @eventDetail))
    FROM EventDetail
    WHERE EventID = @eventID

    SELECT @md5Hash = master.sys.fn_repl_hash_binary(@md5Hash + CONVERT(VARBINARY(MAX), Template))
    FROM XSLTemplate
    WHERE ID = @templateID

    RETURN CONVERT(BIGINT, SUBSTRING(@md5Hash, 0, 8)) ^ CONVERT(BIGINT, SUBSTRING(@md5Hash, 8, 8))
END
GO

CREATE VIEW MeterAssetGroupView
AS
SELECT
    MeterAssetGroup.ID,
    Meter.Name AS MeterName,
    Meter.ID AS MeterID,
    AssetGroupID,
    MeterLocation.Name AS Location
FROM
    MeterAssetGroup JOIN
    Meter ON MeterAssetGroup.MeterID = Meter.ID JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID
GO

CREATE VIEW LineAssetGroupView
AS
SELECT
    LineAssetGroup.ID,
    Line.AssetKey AS LineName,
    (SELECT TOP 1 LineName FROM MeterLine Where LineID = Line.ID) AS LongLineName,
    Line.ID AS LineID,
    AssetGroupID
FROM
    LineAssetGroup JOIN
    Line ON LineAssetGroup.LineID = Line.ID
GO

CREATE VIEW AssetGroupAssetGroupView
AS
SELECT
    AssetGroupAssetGroup.ID,
    AssetGroupAssetGroup.ParentAssetGroupID,
    AssetGroupAssetGroup.ChildAssetGroupID,
    Parent.Name as ParentAssetGroupName,
    Child.Name as ChildAssetGroupName
FROM
    AssetGroupAssetGroup JOIN
    AssetGroup as Parent ON AssetGroupAssetGroup.ParentAssetGroupID = Parent.ID JOIN
    AssetGroup as Child ON AssetGroupAssetGroup.ChildAssetGroupID = Child.ID
GO

CREATE VIEW UserAccountAssetGroupView
AS
SELECT
    UserAccountAssetGroup.ID,
    UserAccountAssetGroup.UserAccountID,
    UserAccountAssetGroup.AssetGroupID,
    UserAccountAssetGroup.Dashboard,
    UserAccountAssetGroup.Email,
    UserAccount.Name AS Username,
    AssetGroup.Name AS GroupName
FROM
    UserAccountAssetGroup JOIN
    UserAccount ON UserAccountAssetGroup.UserAccountID = UserAccount.ID JOIN
    AssetGroup ON UserAccountAssetGroup.AssetGroupID = AssetGroup.ID
GO

ALTER VIEW UserMeter
AS
SELECT DISTINCT
    UserAccount.Name AS UserName,
    Meter.ID AS MeterID
FROM
    UserAccount JOIN
    UserAccountAssetGroup ON UserAccountAssetGroup.UserAccountID = UserAccount.ID LEFT OUTER JOIN
    MeterAssetGroup ON MeterAssetGroup.AssetGroupID = UserAccountAssetGroup.AssetGroupID LEFT OUTER JOIN
    LineAssetGroup ON LineAssetGroup.AssetGroupID = UserAccountAssetGroup.AssetGroupID LEFT OUTER JOIN
    MeterLine ON MeterLine.LineID = LineAssetGroup.LineID JOIN
    Meter ON
        MeterAssetGroup.MeterID = Meter.ID OR
        MeterLine.MeterID = Meter.ID
WHERE
    UserAccount.Approved <> 0 AND
    UserAccountAssetGroup.Dashboard <> 0
GO

-- Each user can update this to create their own scalar stat view in openSEE
CREATE VIEW OpenSEEScalarStatView AS
SELECT
    Event.ID AS EventID,
    MeterLocation.Name AS Station,
    Meter.Name AS Meter,
    Line.AssetKey AS Line,
    EventType.Name AS EventType,
    DATEDIFF(MILLISECOND, Event.StartTime, Event.EndTime)/1000.0 AS FileDuration,
    FaultSummary.Distance,
    FaultSummary.DurationCycles,
    (
        SELECT TOP 1
            (1 - Disturbance.PerUnitMagnitude) * 100 AS SagDepth
        FROM
            Disturbance JOIN
            EventType ON
                Disturbance.EventTypeID = EventType.ID AND
                EventType.Name = 'Sag' JOIN
            Phase ON
                Disturbance.PhaseID = Phase.ID AND
                Phase.Name = 'Worst'
        WHERE
            Disturbance.EventID = Event.ID AND
            Disturbance.StartTime <= dbo.AdjustDateTime2(FaultSummary.Inception, FaultSummary.DurationSeconds) AND
            Disturbance.EndTime >= FaultSummary.Inception
    ) AS SagDepth,
    FaultSummary.IsSelectedAlgorithm,
    EventStat.I2t,
    EventStat.VMax,
    EventStat.VMin,
    EventStat.IMax,
    VAN.Mapping AS VAN,
    VBN.Mapping AS VBN,
    VCN.Mapping AS VCN,
    IAN.Mapping AS IAN,
    IBN.Mapping AS IBN,
    ICN.Mapping AS ICN,
    IR.Mapping AS IR
FROM
    Event JOIN
    Meter ON Event.MeterID = Meter.ID JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID JOIN
    Line ON Event.LineID = Line.ID JOIN
    EventType ON Event.EventTypeID = EventType.ID LEFT OUTER JOIN
    FaultSummary ON
        Event.ID = FaultSummary.EventID AND
        FaultSummary.IsSelectedAlgorithm <> 0 AND
        FaultSummary.FaultNumber = 1 LEFT OUTER JOIN
    EventStat ON Event.ID = EventStat.EventID LEFT OUTER JOIN
    ChannelDetail VAN ON
        Event.MeterID = VAN.MeterID AND
        Event.LineID = VAN.LineID AND
        VAN.MeasurementType = 'Voltage' AND
        VAN.Phase = 'AN' AND
        VAN.MeasurementCharacteristic = 'Instantaneous' AND
        VAN.SeriesType IN ('Values', 'Instantaneous') LEFT OUTER JOIN
    ChannelDetail VBN ON
        Event.MeterID = VBN.MeterID AND
        Event.LineID = VBN.LineID AND
        VBN.MeasurementType = 'Voltage' AND
        VBN.Phase = 'BN' AND
        VBN.MeasurementCharacteristic = 'Instantaneous' AND
        VBN.SeriesType IN ('Values', 'Instantaneous') LEFT OUTER JOIN
    ChannelDetail VCN ON
        Event.MeterID = VCN.MeterID AND
        Event.LineID = VCN.LineID AND
        VCN.MeasurementType = 'Voltage' AND
        VCN.Phase = 'CN' AND
        VCN.MeasurementCharacteristic = 'Instantaneous' AND
        VCN.SeriesType IN ('Values', 'Instantaneous') LEFT OUTER JOIN
    ChannelDetail IAN ON
        Event.MeterID = IAN.MeterID AND
        Event.LineID = IAN.LineID AND
        IAN.MeasurementType = 'Current' AND
        IAN.Phase = 'AN' AND
        IAN.MeasurementCharacteristic = 'Instantaneous' AND
        IAN.SeriesType IN ('Values', 'Instantaneous') LEFT OUTER JOIN
    ChannelDetail IBN ON
        Event.MeterID = IBN.MeterID AND
        Event.LineID = IBN.LineID AND
        IBN.MeasurementType = 'Current' AND
        IBN.Phase = 'BN' AND
        IBN.MeasurementCharacteristic = 'Instantaneous' AND
        IBN.SeriesType IN ('Values', 'Instantaneous') LEFT OUTER JOIN
    ChannelDetail ICN ON
        Event.MeterID = ICN.MeterID AND
        Event.LineID = ICN.LineID AND
        ICN.MeasurementType = 'Current' AND
        ICN.Phase = 'CN' AND
        ICN.MeasurementCharacteristic = 'Instantaneous' AND
        ICN.SeriesType IN ('Values', 'Instantaneous') LEFT OUTER JOIN
    ChannelDetail IR ON
        Event.MeterID = IR.MeterID AND
        Event.LineID = IR.LineID AND
        IR.MeasurementType = 'Current' AND
        IR.Phase = 'RES' AND
        IR.MeasurementCharacteristic = 'Instantaneous' AND
        IR.SeriesType IN ('Values', 'Instantaneous')
GO

ALTER PROCEDURE [dbo].[selectBreakersForMeterIDByDateRange]
    -- Add the parameters for the stored procedure here
    @EventDateFrom as DateTime,
    @EventDateTo as DateTime,
    @MeterID as nvarchar(MAX),
    @username as nvarchar(4000),
    @context as nvarchar(20)
AS
BEGIN

    SET NOCOUNT ON;

DECLARE @startDate DATETIME = @EventDateFrom
DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))

DECLARE @dateStatement NVARCHAR(200) = N'CAST(TripCoilEnergized AS Date)'
DECLARE @groupByStatement NVARCHAR(200) = N'CAST(TripCoilEnergized AS Date)'

IF @context = 'day'
BEGIN
    SET @endDate = DATEADD(DAY, 1, @startDate)
    SET @dateStatement = N'DateAdd(HOUR,DatePart(HOUR,TripCoilEnergized), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(HOUR, TripCoilEnergized), DateAdd(HOUR,DatePart(HOUR,TripCoilEnergized), @EventDateFrom)'
END

if @context = 'hour'
BEGIN
    SET @endDate = DATEADD(HOUR, 1, @startDate)
    SET @dateStatement = N'DateAdd(MINUTE,DatePart(MINUTE,TripCoilEnergized), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(MINUTE, TripCoilEnergized), DateAdd(MINUTE,DatePart(MINUTE,TripCoilEnergized), @EventDateFrom)'
END

if @context = 'minute'
BEGIN
    SET @endDate = DATEADD(MINUTE, 1, @startDate)
    SET @dateStatement = N'DateAdd(SECOND,DatePart(SECOND,TripCoilEnergized), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(SECOND, TripCoilEnergized), DateAdd(SECOND,DatePart(SECOND,TripCoilEnergized), @EventDateFrom)'
END

DECLARE @PivotColumns NVARCHAR(MAX) = N''
DECLARE @ReturnColumns NVARCHAR(MAX) = N''
DECLARE @SQLStatement NVARCHAR(MAX) = N''

create table #TEMP (Name varchar(max))
insert into #TEMP SELECT Name FROM (Select Distinct Name FROM BreakerOperationType) as t

SELECT @PivotColumns = @PivotColumns + '[' + COALESCE(CAST(Name as varchar(max)), '') + '],'
FROM #TEMP ORDER BY Name desc

SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + COALESCE(CAST(Name as varchar(max)), '') + '], 0) AS [' + COALESCE(CAST(Name as varchar(max)), '') + '],'
FROM #TEMP ORDER BY Name desc

DROP TABLE #TEMP

SET @SQLStatement =
' SELECT *                                                                                                   ' +
' INTO #authMeters                                                                                           ' +
' FROM authMeters(@username)                                                                                 ' +
'                                                                                                            ' +
' SELECT *                                                                                                   ' +
' INTO #selectedMeters                                                                                       ' +
' FROM String_To_Int_Table(@MeterID, '','')                                                                  ' +
'                                                                                                            ' +
' SELECT Date as thedate, ' + SUBSTRING(@ReturnColumns,0, LEN(@ReturnColumns)) +
' FROM (                                                                                                     ' +
'   SELECT ' + @dateStatement + '  AS Date,                                                          ' +
'          BreakerOperationType.Name,                                                                        ' +
'          COUNT(*) AS thecount                                                                              ' +
'   FROM BreakerOperation JOIN                                                                               ' +
'        BreakerOperationType ON BreakerOperation.BreakerOperationTypeID = BreakerOperationType.ID JOIN      ' +
'        Event ON Event.ID = BreakerOperation.EventID                                                        ' +
'   WHERE MeterID in (select * from #authMeters) AND                                                         ' +
'         MeterID IN (SELECT * FROM #selectedMeters) AND                                                     ' +
'         TripCoilEnergized >= @startDate AND TripCoilEnergized < @endDate                                   ' +
'   GROUP BY ' + @groupByStatement + ', BreakerOperationType.Name                                        ' +
') as table1                                                                                                 ' +
' PIVOT(                                                                                                     ' +
'       SUM(table1.thecount)                                                                                 ' +
'       FOR table1.Name IN(' + SUBSTRING(@PivotColumns,0, LEN(@PivotColumns)) + ')                           ' +
' ) as pvt                                                                                                   ' +
' ORDER BY Date                                                                                   '

exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterID nvarchar(MAX), @startDate DATETIME, @endDate DATETIME, @EventDateFrom DateTime ', @username = @username, @MeterID = @MeterID, @startDate = @startDate, @endDate = @endDate, @EventDateFrom = @EventDateFrom


END
GO

ALTER PROCEDURE [dbo].[selectDisturbancesForMeterIDByDateRange]

    @EventDateFrom as DateTime,
    @EventDateTo as DateTime,
    @MeterID as nvarchar(MAX),
    @username as nvarchar(4000),
    @context as nvarchar(20)
AS
BEGIN

    SET NOCOUNT ON;

DECLARE @startDate DATETIME = @EventDateFrom
DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))

DECLARE @dateStatement NVARCHAR(200) = N'CAST(Disturbance.StartTime AS Date)'
DECLARE @groupByStatement NVARCHAR(200) = N'CAST(Disturbance.StartTime AS Date)'

IF @context = 'day'
BEGIN
    SET @endDate = DATEADD(DAY, 1, @startDate)
    SET @dateStatement = N'DateAdd(HOUR,DatePart(HOUR,Disturbance.StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(HOUR, Disturbance.StartTime), DateAdd(HOUR,DatePart(HOUR,Disturbance.StartTime), @EventDateFrom)'
END

if @context = 'hour'
BEGIN
    SET @endDate = DATEADD(HOUR, 1, @startDate)
    SET @dateStatement = N'DateAdd(MINUTE,DatePart(MINUTE,Disturbance.StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(MINUTE, Disturbance.StartTime), DateAdd(MINUTE,DatePart(MINUTE,Disturbance.StartTime), @EventDateFrom)'
END

if @context = 'minute'
BEGIN
    SET @endDate = DATEADD(MINUTE, 1, @startDate)
    SET @dateStatement = N'DateAdd(SECOND,DatePart(SECOND,Disturbance.StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(SECOND, Disturbance.StartTime), DateAdd(SECOND,DatePart(SECOND,Disturbance.StartTime), @EventDateFrom)'
END

DECLARE @voltageEnvelope varchar(max) = (SELECT TOP 1 Value FROM Setting WHERE Name = 'DefaultVoltageEnvelope')


DECLARE @PivotColumns NVARCHAR(MAX) = N''
DECLARE @ReturnColumns NVARCHAR(MAX) = N''
DECLARE @SQLStatement NVARCHAR(MAX) = N''

create table #TEMP (Name varchar(max))
insert into #TEMP SELECT SeverityCode FROM (Select Distinct SeverityCode FROM DisturbanceSeverity) as t

SELECT @PivotColumns = @PivotColumns + '[' + COALESCE(CAST(Name as varchar(5)), '') + '],'
FROM #TEMP WHERE Name != 0 ORDER BY Name desc
SET @PivotColumns = @PivotColumns + '[0]'

SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + COALESCE(CAST(Name as varchar(5)), '0') + '], 0) AS [' + COALESCE(CAST(Name as varchar(5)), '') + '],'
FROM #TEMP WHERE Name != 0 ORDER BY Name desc
SET @ReturnColumns = @ReturnColumns + 'COALESCE([0],0) as [0]'

SET @SQLStatement =
N'
DECLARE @user varchar(max) = @username
DECLARE @ids varchar(max) = @MeterID
DECLARE @start DateTime = @startDate
DECLARE @end DateTime = @endDate

SELECT *
INTO #authMeters
FROM authMeters(@user)

SELECT *
INTO #selectedMeters
FROM String_To_Int_Table(@ids, '','')

SELECT DisturbanceDate as thedate, ' + @ReturnColumns + '
 FROM (
    SELECT
        ' + @dateStatement + ' AS DisturbanceDate,
        SeverityCode,
        COUNT(*) AS DisturbanceCount
    FROM
        DisturbanceSeverity JOIN
        Disturbance ON Disturbance.ID = DisturbanceSeverity.DisturbanceID JOIN
        Event ON Event.ID = Disturbance.EventID JOIN
        Phase ON Disturbance.PhaseID = Phase.ID JOIN
        VoltageEnvelope ON VoltageEnvelope.ID = DisturbanceSeverity.VoltageEnvelopeID
    WHERE
        (
            @MeterID = ''0'' OR
            MeterID IN (SELECT * FROM #selectedMeters)
        ) AND
        MeterID IN (SELECT * FROM #authMeters) AND
        Phase.Name = ''Worst'' AND
        VoltageEnvelope.Name = COALESCE(@voltageEnvelope, ''ITIC'') AND
        Disturbance.StartTime BETWEEN @start AND @end AND
        Disturbance.StartTime <> @endDate
    GROUP BY ' + @groupByStatement + ', SeverityCode
    ) As DisturbanceDate
 PIVOT(
        SUM(DisturbanceDate.DisturbanceCount)
        FOR DisturbanceDate.SeverityCode IN(' + @PivotColumns + ')
 ) as pvt
 ORDER BY DisturbanceDate '
print @sqlstatement
exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterID nvarchar(MAX), @startDate DATETIMe, @endDate DATEtime, @EventDateFrom DATETIME, @voltageEnvelope VARCHAR(MAX)', @username = @username, @MeterID = @MeterID, @startDate = @startDate, @endDate = @endDate, @EventDateFrom = @EventDateFrom, @voltageEnvelope = @voltageEnvelope

END
GO

ALTER PROCEDURE [dbo].[selectEventsForMeterIDByDateRange]
    -- Add the parameters for the stored procedure here
    @EventDateFrom as DateTime,
    @EventDateTo as DateTime,
    @MeterID as nvarchar(MAX),
    @username as nvarchar(4000),
    @context as nvarchar(20)

AS
BEGIN

    SET NOCOUNT ON;

DECLARE @startDate DATETIME = @EventDateFrom
DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))

DECLARE @dateStatement NVARCHAR(200) = N'CAST(StartTime AS Date)'
DECLARE @groupByStatement NVARCHAR(200) = N'CAST(StartTime AS Date)'

IF @context = 'day'
BEGIN
    SET @endDate = DATEADD(DAY, 1, @startDate)
    SET @dateStatement = N'DateAdd(HOUR,DatePart(HOUR,StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(HOUR, StartTime), DateAdd(HOUR,DatePart(HOUR,StartTime), @EventDateFrom)'
END

if @context = 'hour'
BEGIN
    SET @endDate = DATEADD(HOUR, 1, @startDate)
    SET @dateStatement = N'DateAdd(MINUTE,DatePart(MINUTE,StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(MINUTE, StartTime), DateAdd(MINUTE,DatePart(MINUTE,StartTime), @EventDateFrom)'
END

if @context = 'minute'
BEGIN
    SET @endDate = DATEADD(MINUTE, 1, @startDate)
    SET @dateStatement = N'DateAdd(SECOND,DatePart(SECOND,StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(SECOND, StartTime), DateAdd(SECOND,DatePart(SECOND,StartTime), @EventDateFrom)'
END



DECLARE @PivotColumns NVARCHAR(MAX) = N''
DECLARE @ReturnColumns NVARCHAR(MAX) = N''
DECLARE @SQLStatement NVARCHAR(MAX) = N''

SELECT @PivotColumns = @PivotColumns + '[' + t.Name + '],'
FROM (Select Name FROM EventType) AS t

SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + t.Name + '], 0) AS [' + t.Name + '],'
FROM (Select Name FROM EventType) AS t

SET @SQLStatement =
'
DECLARE @user varchar(max) = @username
DECLARE @ids varchar(max) = @MeterID
DECLARE @start DateTime = @startDate
DECLARE @end DateTime = @endDate

SELECT *
INTO #authMeters
FROM authMeters(@user)

SELECT *
INTO #selectedMeters
FROM String_To_Int_Table(@ids, '','')

SELECT Date as thedate, ' + SUBSTRING(@ReturnColumns,0, LEN(@ReturnColumns)) + '
FROM (
        SELECT ' + @dateStatement + ' as Date, COUNT(*) AS EventCount, EventType.Name as Name
        FROM Event JOIN
        EventType ON Event.EventTypeID = EventType.ID
       WHERE
            MeterID in (select * from #authMeters) AND
            MeterID IN (SELECT * FROM #selectedMeters) AND
             StartTime >= @start AND StartTime < @end
       GROUP BY ' + @groupByStatement + ', EventType.Name
       ) as ed
 PIVOT(
        SUM(ed.EventCount)
        FOR ed.Name IN(' + SUBSTRING(@PivotColumns,0, LEN(@PivotColumns)) + ')
 ) as pvt
 ORDER BY Date '

--print @startDate
--print @endDate
print @sqlstatement

exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterID nvarchar(MAX), @startDate DATETIME, @endDate DATETIME, @EventDateFrom DATETIME ', @username = @username, @MeterID = @MeterID, @startDate = @startDate, @endDate = @endDate, @EventDateFrom = @EventDateFrom


END
GO

ALTER PROCEDURE [dbo].[selectFaultsForMeterIDByDateRange]
    @EventDateFrom as DateTime,
    @EventDateTo as DateTime,
    @MeterID as nvarchar(MAX),
    @username as nvarchar(4000),
    @context as nvarchar(20)
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @startDate DATETIME = @EventDateFrom
DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))

DECLARE @dateStatement NVARCHAR(200) = N'CAST(Event.StartTime AS Date)'
DECLARE @groupByStatement NVARCHAR(200) = N'CAST(Event.StartTime AS Date)'

IF @context = 'day'
BEGIN
    SET @endDate = DATEADD(DAY, 1, @startDate)
    SET @dateStatement = N'DateAdd(HOUR,DatePart(HOUR,Event.StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(HOUR, Event.StartTime), DateAdd(HOUR,DatePart(HOUR,Event.StartTime), @EventDateFrom)'
END

if @context = 'hour'
BEGIN
    SET @endDate = DATEADD(HOUR, 1, @startDate)
    SET @dateStatement = N'DateAdd(MINUTE,DatePart(MINUTE,Event.StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(MINUTE, Event.StartTime), DateAdd(MINUTE,DatePart(MINUTE,Event.StartTime), @EventDateFrom)'
END

if @context = 'minute'
BEGIN
    SET @endDate = DATEADD(MINUTE, 1, @startDate)
    SET @dateStatement = N'DateAdd(SECOND,DatePart(SECOND,Event.StartTime), @EventDateFrom)'
    SET @groupByStatement = N'DATEPART(SECOND, Event.StartTime), DateAdd(SECOND,DatePart(SECOND,Event.StartTime), @EventDateFrom)'
END



DECLARE @PivotColumns NVARCHAR(MAX) = N''
DECLARE @ReturnColumns NVARCHAR(MAX) = N''
DECLARE @SQLStatement NVARCHAR(MAX) = N''

SELECT @PivotColumns = @PivotColumns + '[' + COALESCE(CAST(t.VoltageKV as varchar(max)), '') + '],'
FROM (Select Distinct Line.VoltageKV
        FROM Line) AS t

SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + COALESCE(CAST(t.VoltageKV as varchar(max)), '') + '], 0) AS [' + COALESCE(CAST(t.VoltageKV as varchar(max)), '') + '],'
FROM (Select Distinct Line.VoltageKV
        FROM Line) AS t

SET @SQLStatement =
' SELECT * ' +
' INTO #authMeters ' +
' FROM authMeters(@username) ' +
' ' +
' SELECT * ' +
' INTO #selectedMeters ' +
' FROM String_To_Int_Table(@MeterID, '','') ' +
' ' +
' SELECT Date as thedate, ' + SUBSTRING(@ReturnColumns,0, LEN(@ReturnColumns)) +
' FROM ( ' +
'       SELECT ' + @dateStatement + ' AS Date, Line.VoltageKV, COUNT(*) AS thecount ' +
'       FROM Event JOIN '+
'       EventType ON Event.EventTypeID = EventType.ID JOIN ' +
'       Line ON Event.LineID = Line.ID ' +
'       WHERE EventType.Name = ''Fault'' AND ' +
'       MeterID in (select * from #authMeters) AND MeterID IN (SELECT * FROM #selectedMeters) AND Event.StartTime >= @startDate AND Event.StartTime < @endDate  ' +
'       GROUP BY ' + @groupByStatement + ', EventType.Name, Line.VoltageKV ' +
'       ) as eventtable ' +
' PIVOT( ' +
'       SUM(eventtable.thecount) ' +
'       FOR eventtable.VoltageKV IN(' + SUBSTRING(@PivotColumns,0, LEN(@PivotColumns)) + ') ' +
' ) as pvt ' +
' ORDER BY Date '

exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterID nvarchar(MAX), @startDate DATETIME, @endDate DATETIME, @EventDateFrom DateTime ', @username = @username, @MeterID = @MeterID, @startDate = @startDate, @endDate = @endDate, @EventDateFrom = @EventDateFrom
END
GO

ALTER PROCEDURE [dbo].[selectMeterLocationsBreakers]
    @EventDateFrom DATETIME,
    @EventDateTo DATETIME,
    @meterIds AS varchar(max),
    @username as nvarchar(4000),
    @context as nvarchar(20)
AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @startDate DATETIME = @EventDateFrom
    DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))


    IF @context = 'day'
    BEGIN
        SET @endDate = DATEADD(DAY, 1, @startDate)
    END

    if @context = 'hour'
    BEGIN
        SET @endDate = DATEADD(HOUR, 1, @startDate)
    END

    if @context = 'minute'
    BEGIN
        SET @endDate = DATEADD(MINUTE, 1, @startDate)
    END

    if @context = 'second'
    BEGIN
        SET @endDate = DATEADD(SECOND, 1, @startDate)
    END

    DECLARE @PivotColumns NVARCHAR(MAX) = N''
    DECLARE @CountColumns NVARCHAR(MAX) = N''
    DECLARE @ReturnColumns NVARCHAR(MAX) = N''
    DECLARE @SQLStatement NVARCHAR(MAX) = N''

    create table #TEMP (Name varchar(max))
    insert into #TEMP SELECT Name FROM (Select Distinct Name FROM BreakerOperationType) as t

    SELECT @PivotColumns = @PivotColumns + '[' + COALESCE(CAST(Name as varchar(max)), '') + '],'
    FROM #TEMP ORDER BY Name desc

    SELECT @CountColumns = @CountColumns + 'COALESCE([' + COALESCE(CAST(Name as varchar(20)), '') + '], 0) + '
    FROM #TEMP ORDER BY Name desc

    SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + COALESCE(CAST(Name as varchar(max)), '') + '], 0) AS [' + COALESCE(CAST(Name as varchar(max)), '') + '],'
    FROM #TEMP ORDER BY Name desc

    DROP TABLE #TEMP


    SET @SQLStatement =
    'SELECT *
    INTO #authMeters
    FROM authMeters(@username)

    SELECT *
    INTO #selectedMeters
    FROM String_To_Int_Table(@MeterIds, '','')

    SELECT Meter.ID,
             Meter.Name,
             MeterLocation.Longitude,
             MeterLocation.Latitude,
             ' + SUBSTRING(@CountColumns,0, LEN(@CountColumns)) +' as Count,
             ' + SUBSTRING(@ReturnColumns,0, LEN(@ReturnColumns)) + '
    FROM
        Meter JOIN
        MeterLocation ON Meter.MeterLocationID = MeterLocation.ID LEFT OUTER JOIN
        (
            SELECT MeterID,
                   COUNT(*) AS EventCount,
                   BreakerOperationType.Name as OperationType
            FROM BreakerOperation JOIN
                 Event ON BreakerOperation.EventID = Event.ID JOIN
                 EventType ON Event.EventTypeID = EventType.ID JOIN
                 BreakerOperationType ON BreakerOperation.BreakerOperationTypeID = BreakerOperationType.ID
            WHERE
                 TripCoilEnergized >= @startDate AND TripCoilEnergized < @endDate
            GROUP BY Event.MeterID, BreakerOperationType.Name
           ) as ed
           PIVOT(
                 SUM(ed.EventCount)
                 FOR ed.OperationType IN(' + SUBSTRING(@PivotColumns,0, LEN(@PivotColumns)) + ')
           ) as pvt On pvt.MeterID = meter.ID
    WHERE
        Meter.ID in (select * from #authMeters) AND
        Meter.ID IN (SELECT * FROM #selectedMeters)

    ORDER BY Meter.Name'

    print @SQLStatement
    exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterIds nvarchar(MAX), @startDate DATETIME, @endDate DATETIME, @EventDateFrom DATETIME ', @username = @username, @MeterIds = @MeterIds, @startDate = @startDate, @endDate = @endDate, @EventDateFrom = @EventDateFrom

END
GO

ALTER PROCEDURE [dbo].[selectMeterLocationsDisturbances]

    @EventDateFrom as DateTime,
    @EventDateTo as DateTime,
    @meterIds AS varchar(max),
    @username as nvarchar(4000),
    @context as nvarchar(20)
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @startDate DATETIME = @EventDateFrom
DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))


IF @context = 'day'
BEGIN
    SET @endDate = DATEADD(DAY, 1, @startDate)
END

if @context = 'hour'
BEGIN
    SET @endDate = DATEADD(HOUR, 1, @startDate)
END

if @context = 'minute'
BEGIN
    SET @endDate = DATEADD(MINUTE, 1, @startDate)
END

if @context = 'second'
BEGIN
    SET @endDate = DATEADD(SECOND, 1, @startDate)
END


DECLARE @PivotColumns NVARCHAR(MAX) = N''
DECLARE @CountColumns NVARCHAR(MAX) = N''
DECLARE @ReturnColumns NVARCHAR(MAX) = N''
DECLARE @SQLStatement NVARCHAR(MAX) = N''


create table #TEMP (Name varchar(max))
insert into #TEMP SELECT SeverityCode FROM (Select Distinct SeverityCode FROM DisturbanceSeverity) as t

SELECT @PivotColumns = @PivotColumns + '[' + COALESCE(CAST(Name as varchar(5)), '') + '],'
FROM #TEMP WHERE Name != 0 ORDER BY Name desc
SET @PivotColumns = @PivotColumns + '[0]'

SELECT @CountColumns = @CountColumns + 'COALESCE([' + COALESCE(CAST(Name as varchar(5)), '') + '], 0) + '
FROM #TEMP WHERE Name != 0 ORDER BY Name desc
SET @CountColumns = @CountColumns + 'COALESCE([0], 0) '


SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + COALESCE(CAST(Name as varchar(5)), '') + '], 0) AS [' + COALESCE(CAST(Name as varchar(5)), '') + '],'
FROM #TEMP WHERE Name != 0ORDER BY Name desc
SET @ReturnColumns = @ReturnColumns + 'COALESCE([0], 0) as [0]'

DECLARE @voltageEnvelope varchar(max) = (SELECT TOP 1 Value FROM Setting WHERE Name = 'DefaultVoltageEnvelope')

DROP TABLE #TEMP

SET @SQLStatement = N'
DECLARE @user varchar(max) = @username
DECLARE @ids varchar(max) = @MeterIds
DECLARE @start DateTime = @startDate
DECLARE @end DateTime = @endDate

SELECT *
INTO #authMeters
FROM authMeters(@user)

SELECT *
INTO #selectedMeters
FROM String_To_Int_Table(@ids, '','')

SELECT Meter.ID,
         Meter.Name,
         MeterLocation.Longitude,
         MeterLocation.Latitude,
         ' + @CountColumns +' as Count,
         ' + @ReturnColumns + '
FROM
    Meter JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID LEFT OUTER JOIN
    (
        SELECT MeterID,
               COUNT(*) AS EventCount,
               SeverityCode
        FROM Event JOIN
             Disturbance ON Event.ID = Disturbance.EventID JOIN
             Phase ON Phase.ID = Disturbance.PhaseID LEFT JOIN
             DisturbanceSeverity ON Disturbance.ID = DisturbanceSeverity.DisturbanceID JOIN
             VoltageEnvelope ON VoltageEnvelope.ID = DisturbanceSeverity.VoltageEnvelopeID
        WHERE
             Phase.Name = ''Worst'' AND
             Disturbance.StartTime >= @start AND Disturbance.StartTime < @end AND
             VoltageEnvelope.Name = COALESCE(@voltageEnvelope, ''ITIC'')
        GROUP BY Event.MeterID, SeverityCode
       ) as ed
       PIVOT(
             SUM(ed.EventCount)
             FOR ed.SeverityCode IN(' + @PivotColumns + ')
       ) as pvt On pvt.MeterID = meter.ID
    WHERE
        Meter.ID in (select * from #authMeters) AND
        Meter.ID IN (SELECT * FROM #selectedMeters)

Order By Name '

print @SqlStatement
exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterIds nvarchar(MAX), @startDate DATETIME, @endDate DATETIME , @voltageEnvelope VARCHAR(MAX)', @username = @username, @MeterIds = @MeterIds, @startDate = @startDate, @endDate = @endDate, @voltageEnvelope = @voltageEnvelope

END
GO

ALTER PROCEDURE [dbo].[selectMeterLocationsEvents]
    @EventDateFrom DATETIME,
    @EventDateTo DATETIME,
    @meterIds AS varchar(max),
    @username as nvarchar(4000),
    @context as nvarchar(20)

AS
BEGIN

    SET NOCOUNT ON;
DECLARE @startDate DATETIME = @EventDateFrom
DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))


IF @context = 'day'
BEGIN
    SET @endDate = DATEADD(DAY, 1, @startDate)
END

if @context = 'hour'
BEGIN
    SET @endDate = DATEADD(HOUR, 1, @startDate)
END

if @context = 'minute'
BEGIN
    SET @endDate = DATEADD(MINUTE, 1, @startDate)
END

if @context = 'second'
BEGIN
    SET @endDate = DATEADD(SECOND, 1, @startDate)
END


DECLARE @PivotColumns NVARCHAR(MAX) = N''
DECLARE @CountColumns NVARCHAR(MAX) = N''
DECLARE @ReturnColumns NVARCHAR(MAX) = N''
DECLARE @SQLStatement NVARCHAR(MAX) = N''

SELECT @PivotColumns = @PivotColumns + '[' + t.Name + '],'
FROM (Select Name FROM EventType) AS t

SELECT @CountColumns = @CountColumns + 'COALESCE([' + t.Name + '], 0) + '
FROM (Select Name FROM EventType) AS t


SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + t.Name + '], 0) AS [' + t.Name + '],'
FROM (Select Name FROM EventType) AS t

SET @SQLStatement =
'
DECLARE @user varchar(max) = @username
DECLARE @ids varchar(max) = @MeterIds
DECLARE @start DateTime = @startDate
DECLARE @end DateTime = @endDate

SELECT *
INTO #authMeters
FROM authMeters(@user)

SELECT *
INTO #selectedMeters
FROM String_To_Int_Table(@ids, '','')

SELECT Meter.ID,
         Meter.Name,
         MeterLocation.Longitude,
         MeterLocation.Latitude,
         ' + SUBSTRING(@CountColumns,0, LEN(@CountColumns)) +' as Count,
         ' + SUBSTRING(@ReturnColumns,0, LEN(@ReturnColumns)) + '
FROM
    Meter JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID LEFT OUTER JOIN
    (
        SELECT MeterID,
               COUNT(*) AS EventCount,
               EventType.Name as Name

        FROM Event JOIN
             EventType ON Event.EventTypeID = EventType.ID
        WHERE
             StartTime >= @start AND StartTime < @end
        GROUP BY Event.MeterID, EventType.Name
       ) as ed
       PIVOT(
             SUM(ed.EventCount)
             FOR ed.Name IN(' + SUBSTRING(@PivotColumns,0, LEN(@PivotColumns)) + ')
       ) as pvt On pvt.MeterID = meter.ID
WHERE
    Meter.ID in (select * from #authMeters) AND
    Meter.ID IN (SELECT * FROM #selectedMeters)

ORDER BY Meter.Name'

--print @startDate
--print @endDate
print @sqlstatement

exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterIds nvarchar(MAX), @startDate DATETIME, @endDate DATETIME', @username = @username, @MeterIds = @MeterIds, @startDate = @startDate, @endDate = @endDate
END
GO

ALTER PROCEDURE [dbo].[selectMeterLocationsFaults]
    @EventDateFrom DateTime,
    @EventDateTo DateTime,
    @meterIds AS varchar(max),
    @username as nvarchar(4000),
    @context as nvarchar(20)

AS
BEGIN

    SET NOCOUNT ON;

DECLARE @startDate DATETIME = @EventDateFrom
DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))


IF @context = 'day'
BEGIN
    SET @endDate = DATEADD(DAY, 1, @startDate)
END

if @context = 'hour'
BEGIN
    SET @endDate = DATEADD(HOUR, 1, @startDate)
END

if @context = 'minute'
BEGIN
    SET @endDate = DATEADD(MINUTE, 1, @startDate)
END

if @context = 'second'
BEGIN
    SET @endDate = DATEADD(SECOND, 1, @startDate)
END


DECLARE @PivotColumns NVARCHAR(MAX) = N''
DECLARE @CountColumns NVARCHAR(MAX) = N''
DECLARE @ReturnColumns NVARCHAR(MAX) = N''
DECLARE @SQLStatement NVARCHAR(MAX) = N''

SELECT @PivotColumns = @PivotColumns + '[' + COALESCE(CAST(t.VoltageKV as varchar(max)), '') + '],'
FROM (Select Distinct Line.VoltageKV
        FROM Line) AS t

SELECT @CountColumns = @CountColumns + 'COALESCE([' + COALESCE(CAST(t.VoltageKV as varchar(max)), '') + '], 0) + '
FROM (Select Distinct Line.VoltageKV
        FROM Line) AS t

SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + COALESCE(CAST(t.VoltageKV as varchar(max)), '') + '], 0) AS [' + COALESCE(CAST(t.VoltageKV as varchar(max)), '') + '],'
FROM (Select Distinct Line.VoltageKV
        FROM Line) AS t


SET @SQLStatement =
'SELECT *
INTO #authMeters
FROM authMeters(@username)

SELECT *
INTO #selectedMeters
FROM String_To_Int_Table(@MeterIds, '','')

SELECT Meter.ID,
         Meter.Name,
         MeterLocation.Longitude,
         MeterLocation.Latitude,
         ' + SUBSTRING(@CountColumns,0, LEN(@CountColumns)) +' as Count,
         ' + SUBSTRING(@ReturnColumns,0, LEN(@ReturnColumns)) + '
FROM
    Meter JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID LEFT OUTER JOIN
    (
        SELECT MeterID,
               COUNT(*) AS EventCount,
               VoltageKV
        FROM Event JOIN
             EventType ON Event.EventTypeID = EventType.ID JOIN
             Line ON Event.LineID = Line.ID
        WHERE
             StartTime >= @startDate AND StartTime < @endDate AND
             EventType.Name = ''Fault''
        GROUP BY Event.MeterID, VoltageKV
       ) as ed
       PIVOT(
             SUM(ed.EventCount)
             FOR ed.VoltageKV IN(' + SUBSTRING(@PivotColumns,0, LEN(@PivotColumns)) + ')
       ) as pvt On pvt.MeterID = meter.ID
    WHERE
        Meter.ID in (select * from #authMeters) AND
        Meter.ID IN (SELECT * FROM #selectedMeters)

ORDER BY Meter.Name'

print @SQLStatement
exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterIds nvarchar(MAX), @startDate DATETIME, @endDate DATETIME, @EventDateFrom DATETIME ', @username = @username, @MeterIds = @MeterIds, @startDate = @startDate, @endDate = @endDate, @EventDateFrom = @EventDateFrom

END
GO

ALTER PROCEDURE [dbo].[selectMeterLocationsExtensions]
    @EventDateFrom DATETIME,
    @EventDateTo DATETIME,
    @meterIds AS varchar(max),
    @username as nvarchar(4000),
    @context as nvarchar(20)

AS
BEGIN

    SET NOCOUNT ON;
DECLARE @startDate DATETIME = @EventDateFrom
DECLARE @endDate DATETIME = DATEADD(DAY, 1, CAST(@EventDateTo AS DATE))


IF @context = 'day'
BEGIN
    SET @endDate = DATEADD(DAY, 1, @startDate)
END

if @context = 'hour'
BEGIN
    SET @endDate = DATEADD(HOUR, 1, @startDate)
END

if @context = 'minute'
BEGIN
    SET @endDate = DATEADD(MINUTE, 1, @startDate)
END

if @context = 'second'
BEGIN
    SET @endDate = DATEADD(SECOND, 1, @startDate)
END


DECLARE @PivotColumns NVARCHAR(MAX) = N''
DECLARE @CountColumns NVARCHAR(MAX) = N''
DECLARE @ReturnColumns NVARCHAR(MAX) = N''
DECLARE @SQLStatement NVARCHAR(MAX) = N''
DECLARE @MiddleStatment NVARCHAR(MAX) = N''

SELECT * INTO #temp
FROM EVENT
WHERE   StartTime Between @startDate AND @endDate AND
        MeterID in (select * from authMeters(@username)) AND
        MeterID IN (SELECT * FROM String_To_Int_Table( @meterIds,  ','))

CREATE INDEX tempIndex ON #temp (MeterID)

CREATE TABLE #easTable( MeterID int, ServiceName varchar(max), EventCount int);

SELECT @PivotColumns = @PivotColumns + '[' + t.ServiceName + '],'
FROM (Select ServiceName FROM EASExtension) AS t

SELECT @CountColumns = @CountColumns + 'COALESCE([' + t.ServiceName + '], 0) + '
FROM (Select ServiceName FROM EASExtension) AS t


SELECT @ReturnColumns = @ReturnColumns + ' COALESCE([' + t.ServiceName + '], 0) AS [' + t.ServiceName + '],'
FROM (Select ServiceName FROM EASExtension) AS t

DECLARE @serviceName as varchar(max);
DECLARE @hasResultFunction as varchar(max);

DECLARE aCursor CURSOR FOR
SELECT ServiceName, HasResultFunction FROM EASExtension
OPEN aCursor;
FETCH NEXT FROM aCursor into @serviceName, @hasResultFunction;
WHILE @@FETCH_STATUS = 0
   BEGIN
    DECLARE @Sql nvarchar(max) = N'
            INSERT INTO #easTable
            SELECT MeterID,
                '''+ @serviceName + ''' as ServiceName,
                Count(*) as EventCount
            FROM    #temp
            WHERE   dbo.' + @hasResultFunction + '(ID) != ''''
            GROUP BY MeterID'
    exec sp_executesql @sql
    FETCH NEXT FROM aCursor into @serviceName, @hasResultFunction;
   END;
CLOSE aCursor;
DEALLOCATE aCursor;


SELECT @MiddleStatment = @MiddleStatment +  '
            SELECT MeterID,
                '''+ t.ServiceName + ''' as ServiceName,
                Count(*) as EventCount
            FROM    #temp
            WHERE   dbo.' + t.HasResultFunction + '(ID) != ''''
            GROUP BY MeterID UNION'

FROM (Select * FROM EASExtension) AS t

SET @SQLStatement =
'SELECT *
INTO #authMeters
FROM authMeters(@username)

SELECT *
INTO #selectedMeters
FROM String_To_Int_Table(@MeterIds, '','')

SELECT Meter.ID,
         Meter.Name,
         MeterLocation.Longitude,
         MeterLocation.Latitude,
         ' + SUBSTRING(@CountColumns,0, LEN(@CountColumns)) +' as Count,
         ' + SUBSTRING(@ReturnColumns,0, LEN(@ReturnColumns)) + '
FROM
    Meter JOIN
    MeterLocation ON Meter.MeterLocationID = MeterLocation.ID LEFT OUTER JOIN
    #easTable as ed
       PIVOT(
             SUM(ed.EventCount)
             FOR ed.ServiceName IN(' + SUBSTRING(@PivotColumns,0, LEN(@PivotColumns)) + ')
       ) as pvt On pvt.MeterID = meter.ID
WHERE
    Meter.ID in (select * from #authMeters) AND
    Meter.ID IN (SELECT * FROM #selectedMeters)

ORDER BY Meter.Name

DROP TABLE #temp
DROP TABLE #easTable
'
--print @startDate
--print @endDate
print @sqlstatement

exec sp_executesql @SQLStatement, N'@username nvarchar(4000), @MeterIds nvarchar(MAX), @startDate DATETIME, @endDate DATETIME, @EventDateFrom DATETIME ', @username = @username, @MeterIds = @MeterIds, @startDate = @startDate, @endDate = @endDate, @EventDateFrom = @EventDateFrom

END

GO

ALTER PROCEDURE [dbo].[selectSiteLinesDisturbanceDetailsByDate]
    -- Add the parameters for the stored procedure here
    @EventDate as DateTime,
    @MeterID as nvarchar(4000),
    @context as nvarchar(20)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @worstPhaseID INT = (SELECT ID FROM Phase WHERE Name = 'Worst')
    DECLARE @startDate DATETIME = @EventDate
    DECLARE @endDate DATETIME


    IF @context = 'day'
    BEGIN
        SET @startDate = DATEADD(DAY, DATEDIFF(DAY, 0, @EventDate), 0)
        SET @endDate = DATEADD(DAY, 1, @startDate)
    END

    if @context = 'hour'
    BEGIN
        SET @startDate = DATEADD(HOUR, DATEDIFF(HOUR, 0, @EventDate), 0)
        SET @endDate = DATEADD(HOUR, 1, @startDate)
    END

    if @context = 'minute'
    BEGIN
        SET @startDate = DATEADD(MINUTE, DATEDIFF(MINUTE, 0, @EventDate), 0)
        SET @endDate = DATEADD(MINUTE, 1, @startDate)
    END

    if @context = 'second'
    BEGIN
        DECLARE @tempDate DATETIME = DATEADD(DAY, DATEDIFF(DAY, 0, @EventDate), 0)
        SET @startDate = DATEADD(SECOND, DATEDIFF(SECOND, @tempDate, @EventDate), @tempDate)
        SET @endDate = DATEADD(SECOND, 1, @startDate)
    END

    DECLARE @voltageEnvelope varchar(max) = (SELECT TOP 1 Value FROM Setting WHERE Name = 'DefaultVoltageEnvelope')

    SELECT
        Event.LineID AS thelineid,
        Event.ID AS theeventid,
        Disturbance.ID as disturbanceid,
        EventType.Name AS disturbancetype,
        Phase.Name AS phase,
        CASE Disturbance.PerUnitMagnitude
            WHEN -1E308 THEN 'NaN'
            ELSE CAST(Disturbance.PerUnitMagnitude AS VARCHAR(MAX))
        END AS magnitude,
        CASE Disturbance.DurationSeconds
            WHEN -1E308 THEN 'NaN'
            ELSE CAST(CONVERT(DECIMAL(10,3), Disturbance.DurationSeconds) AS VARCHAR(14))
        END AS duration,
        CAST(Disturbance.StartTime AS VARCHAR(26)) AS theinceptiontime,
        dbo.DateDiffTicks('1970-01-01', Disturbance.StartTime) / 10000.0 AS startmillis,
        dbo.DateDiffTicks('1970-01-01', Disturbance.EndTime) / 10000.0 AS endmillis,
        DisturbanceSeverity.SeverityCode,
        MeterLine.LineName + ' ' + [Line].[AssetKey] AS thelinename,
        Line.VoltageKV AS voltage,
        (SELECT COUNT(*) FROM EventNote WHERE EventID = Event.ID) as notes
    FROM
        Event JOIN
        Disturbance ON Disturbance.EventID = Event.ID JOIN
        Disturbance WorstDisturbance ON
            Disturbance.EventID = WorstDisturbance.EventID AND
            Disturbance.PerUnitMagnitude = WorstDisturbance.PerUnitMagnitude AND
            Disturbance.DurationSeconds = WorstDisturbance.DurationSeconds JOIN
        EventType ON Disturbance.EventTypeID = EventType.ID JOIN
        Phase ON Disturbance.PhaseID = Phase.ID JOIN
        DisturbanceSeverity ON Disturbance.ID = DisturbanceSeverity.DisturbanceID JOIN
        Meter ON Meter.ID = @MeterID JOIN
        Line ON Event.LineID = Line.ID JOIN
        MeterLine ON MeterLine.MeterID = @MeterID AND MeterLine.LineID = Line.ID JOIN
        VoltageEnvelope ON VoltageEnvelope.ID = DisturbanceSeverity.VoltageEnvelopeID
    WHERE
        Event.StartTime >= @startDate AND Event.StartTime < @endDate AND
        Event.MeterID = @MeterID AND
        WorstDisturbance.PhaseID = @worstPhaseID AND
        Disturbance.PhaseID <> @worstPhaseID AND
        VoltageEnvelope.Name = COALESCE(@voltageEnvelope, 'ITIC')
    ORDER BY
        Event.StartTime ASC

END
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('Email.AdminAddress', 'xda-admin@gridprotectionalliance.org', 'xda-admin@gridprotectionalliance.org')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('EventEmail.Enabled', 'True', 'False')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('EventEmail.MaxEmailCount', '0', '0')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('EventEmail.MaxEmailSpan', '0.0', '0.0')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('PQTrendingWebReport.Enabled', 'False', 'False')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('PQTrendingWebReport.Frequency', '0 2 * * *', '0 2 * * *')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('PQTrendingWebReport.Verbose', 'False', 'False')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('StepChangeWebReport.Enabled', 'False', 'False')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('StepChangeWebReport.Frequency', '0 2 * * *', '0 2 * * *')
GO

INSERT INTO Setting(Name, Value, DefaultValue) VALUES('StepChangeWebReport.Verbose', 'False', 'False')
GO

INSERT INTO DashSettings (Name, Value, Enabled) VALUES ('EventsChart', 'Snapshot', 0)
GO

INSERT INTO DashSettings (Name, Value, Enabled) VALUES ('EventsChartColors', 'Snapshot,#9db087', 1)
GO

INSERT INTO DashSettings (Name, Value, Enabled) VALUES ('System.URL', 'http://localhost/PQDashboard', 1)
GO